package com.whatech.mall.order.config;

import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.whatech.mall.order.exception.OrderException;
import com.whatech.mall.order.interceptor.MsJwtValidateInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import unscan.config.GlobalRibbonConfiguration;

import java.io.IOException;

/**
 * 订单服务配置。
 */
@Slf4j
@Configuration
@RibbonClients(defaultConfiguration = GlobalRibbonConfiguration.class)
public class OrderServiceConfiguration extends WebMvcConfigurationSupport {

    @Autowired
    private MsJwtValidateInterceptor msJwtValidateInterceptor;

    @Bean
    @LoadBalanced
    /**
     * RestTemplate整合Sentinel。
     * 可使用 resttemplate.sentinel.enabled=false 配置来关闭 @SentinelRestTemplate 功能
     */
    @SentinelRestTemplate(blockHandler = "restTemplateBlockHandler",
            fallback = "restTemplateFallback")
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        // 自定义接口调用异常处理
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                throw new OrderException("api invoke error, status code: " + response.getRawStatusCode());
            }
        });
        return restTemplate;
    }

    // RestTemplate熔断处理
    public String restTemplateBlockHandler(BlockException e) {
        log.warn("RestTemplate block by Sentinel", e);
        return "";
    }

    // RestTemplate降级处理
    public String restTemplateFallback(Throwable t) {
        log.warn("RestTemplate fallback by Sentinel", t);
        return "";
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(msJwtValidateInterceptor).addPathPatterns("/order/**");
    }

}
